'use strict';
const bcrypt = require('bcrypt');
const { unset, cloneDeep, isArray } = require('lodash');

const { Success, GeneralException } = require('../core/httpException');
const ENV = process.env.NODE_ENV;

const dayjs = require('dayjs');
const crypto = require('crypto');


module.exports = {
  time() {
    return dayjs().format('YYYY-MM-DD HH:mm:ss');
  },
  timestamp(data) {
    return new Date(data).getTime();
  },
  unPick(source, arr) {
    if (Array.isArray(arr)) {
      const obj = {};
      for (const i in source) {
        if (!arr.includes(i)) {
          obj[i] = source[i];
        }
      }
      return obj;
    }
  },

  /**
   * @param {*} returnMessage 提示语
   * @param {*} options 配置参数
   */
  success(options = {}, returnMessage = '') {
    const { bean = {}, beans = [], returnCode = '0000' } = options;
    throw new Success(returnMessage, bean, beans, returnCode);
  },

  /**
   * @param {*} returnMessage 错误提示语
   * @param {*} options 配置
   */
  commonErr(returnMessage, options = {}) {
    const { bean = {}, beans = [], returnCode = '2999' } = options;
    throw new GeneralException(returnMessage, returnCode, bean, beans);
  },

   /**
   * @param {*} returnMessage 错误提示语
   * @param {*} options 配置
   */
  exception(returnMessage, returnCode = '9999', options = {}) {
    const { bean = {}, beans = [] } = options;
    throw new GeneralException(returnMessage, returnCode, bean, beans);
  },

  /**
   * md5加密
   * @param {*} password 
   * @returns 
   */
  md5(string) {
    return crypto.createHash("md5").update(string).digest('hex');
  },

  /**
   * @param {*} password 密码
   */
  encrypt(password) {
    const salt = bcrypt.genSaltSync(10);
    const hash = bcrypt.hashSync(password, salt);
    return hash;
  },

  /**
   * @param {*} password 原始密码
   * @param {*} hash hash
   */
  compare(password, hash) {
    return bcrypt.compareSync(password, hash);
  },

  /**
   * @param {*} data 需要过滤的值
   */
  filterData(data) {
    let handleData = cloneDeep(data);

    // 排除时间字段
    if (isArray(handleData)) {
      handleData.forEach(value => {
        value = value.dataValues ? value.dataValues : value;
        unset(value, 'password');
      });
    } else {
      handleData = handleData.dataValues ? handleData.dataValues : handleData;
      unset(handleData, 'password');
    }
    return handleData;
  },

  // 解析jwt token
  decodeJwt(ctx) {
    const token = ctx.params('header.token');
    const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
    const { id } = decode;
    return id;
  },

  // 获取开发环境
  isDev() {
    return ENV === 'dev';
  },
  isProd() {
    return ENV === 'production';
  },
  isTest() {
    return ENV === 'test';
  },
};
